//
//  BDLoginTableViewController.m
//  BeidouMall
//
//  Created by qie on 16/3/31.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDLoginTableViewController.h"
#import "BDLangageSetTableViewController.h"

@interface BDLoginTableViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *passwordLabel;


@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwrodTextField;

@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *dismissButton;
@property (weak, nonatomic) IBOutlet UIButton *bottomButton1;
@property (weak, nonatomic) IBOutlet UIButton *bottomButton2;
@property (weak, nonatomic) IBOutlet UIButton *bottomButton3;

@end

@implementation BDLoginTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.bottomView.height = kScreen_Height - 204;
    
    if ([[[BDAccountManagerModel shareInstance] phone] length] > 0) {
        self.userNameTextField.text = [[BDAccountManagerModel shareInstance] phone];
    } else if ([[[BDAccountManagerModel shareInstance] email] length] > 0) {
        self.userNameTextField.text = [[BDAccountManagerModel shareInstance] email];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.title = NSLocalizedString(@"loginTitle", nil);
    [self.tableView reloadData];
    CGFloat fontSize = 11.0;
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
        // 标题
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0]}];
        
        fontSize = 11.0;
        _bottomButton1.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        _bottomButton2.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        _bottomButton3.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        
        _userNameLabel.font = [UIFont boldSystemFontOfSize:15.0];
        [_userNameTextField setValue:[UIFont boldSystemFontOfSize:14.0] forKeyPath:@"_placeholderLabel.font"];
        _passwordLabel.font = [UIFont boldSystemFontOfSize:15.0];
        _loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
    } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
        // 标题
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0]}];
        
        fontSize = 15.0;
        _bottomButton1.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        _bottomButton2.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        _bottomButton3.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        _userNameLabel.font = [UIFont boldSystemFontOfSize:16.0];
        [_userNameTextField setValue:[UIFont boldSystemFontOfSize:15.0] forKeyPath:@"_placeholderLabel.font"];
        _passwordLabel.font = [UIFont boldSystemFontOfSize:16.0];
        _loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
    } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        // 标题
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont fontWithName:@"BZDHT" size:12.0]}];
        
        fontSize = 9.0;
        
        _bottomButton1.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:fontSize];
        _bottomButton2.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:fontSize];
        _bottomButton3.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:fontSize];
        _userNameLabel.font = [UIFont fontWithName:@"Bzdbt" size:10.0];
        [_userNameTextField setValue:[UIFont fontWithName:@"Bzdbt" size:10.0] forKeyPath:@"_placeholderLabel.font"];
        _passwordLabel.font = [UIFont fontWithName:@"Bzdbt" size:10.0];
        _loginButton.titleLabel.font = [UIFont fontWithName:@"BZDHT" size:14.0];
    }
    
    
    _userNameLabel.text = NSLocalizedString(@"account:", nil);
    _userNameTextField.placeholder = NSLocalizedString(@"loginHoldPlace", nil);
    _passwordLabel.text = NSLocalizedString(@"password:", nil);
    [_loginButton setTitle:NSLocalizedString(@"login", nil) forState:UIControlStateNormal];
    _loginButton.layer.cornerRadius = 5.0;
    _loginButton.layer.masksToBounds = YES;
    _bottomButton1.layer.cornerRadius = 7.0;
    _bottomButton1.layer.masksToBounds = YES;
    _bottomButton1.layer.borderColor = RGBColor(215, 19, 33).CGColor;
    _bottomButton1.layer.borderWidth = 2.0;
    [_bottomButton1 setTitle:NSLocalizedString(@"fastRegister", nil) forState:UIControlStateNormal];
    [_bottomButton2 setTitle:NSLocalizedString(@"verificationcodelogin", nil) forState:UIControlStateNormal];
    [_bottomButton3 setTitle:NSLocalizedString(@"retrievepassword", nil) forState:UIControlStateNormal];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private method

- (void)changeLanguage {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    BDLangageSetTableViewController *vc = (BDLangageSetTableViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"BDLangageStoryboardID"];
    //    vc.block = ^(NSString *str){
    //        self.title = NSLocalizedString(@"login", nil);
    //        [self.tableView reloadData];
    //    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - TableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 30.0)];
    header.backgroundColor = [UIColor clearColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(kScreen_Width - 75, 0, 75, 30)];
    [btn setTitle:NSLocalizedString(@"langage", nil) forState:UIControlStateNormal];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        btn.titleLabel.font = [UIFont fontWithName:@"BZDHT" size:12.0];
    } else {
        btn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    }
    
    [btn setTitleColor:RGBColor(248, 48, 48) forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(changeLanguage)forControlEvents:UIControlEventTouchDown];
    [header addSubview:btn];
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark - TextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *futrueString = [textField.text changeCharactersInRange:range replacementString:string];
    if (textField == _userNameTextField) {
        _passwrodTextField.text = @"";
        if ([_passwrodTextField.text isValidPassword] && [futrueString length]) {
            _loginButton.enabled = YES;
        } else {
            _loginButton.enabled = NO;
        }
        
        if (futrueString.length > kUserNameLength) {
            return NO;
        }
    } else if (textField == _passwrodTextField) {
        if ([_passwrodTextField.text length] && [futrueString isValidPassword]) {
            _loginButton.enabled = YES;
        } else {
            _loginButton.enabled = NO;
        }
        
        if (futrueString.length > kPasswordMaxLength) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 101) {
        [_passwrodTextField becomeFirstResponder];
    } else if (textField.tag == 102) {
        [textField resignFirstResponder];
        [self loginButtonPressed:nil];
    }
    return YES;
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_userNameTextField.isFirstResponder) {
        [_userNameTextField resignFirstResponder];
    } else if (_passwrodTextField.isFirstResponder) {
        [_passwrodTextField resignFirstResponder];
    }
}

#pragma mark - IBAction

- (IBAction)switchButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
    _passwrodTextField.secureTextEntry = !sender.selected;
}

- (IBAction)loginButtonPressed:(UIButton *)sender {
    if (_userNameTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Account is blank", nil)];
    } else if (!([_userNameTextField.text isValidPhoneNum] || [_userNameTextField.text isVaildEmail])) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Account format is invalid", nil)];
    } else if (_passwrodTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Password is blank", nil)];
    } else if (![_passwrodTextField.text isValidPassword]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Password format is invalid", nil)];
    } else {
        if (_userNameTextField.isFirstResponder) {
            [_userNameTextField resignFirstResponder];
        } else if (_passwrodTextField.isFirstResponder) {
            [_passwrodTextField resignFirstResponder];
        }
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"Login now", nil)];
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[[BDNetworking shareInstance] baseUrl],LOGIN_IN];
        [[BDAccountManagerModel shareInstance]
         loginWithUrl:url
         username:_userNameTextField.text
         password:_passwrodTextField.text
         userType:BUYER
         completionHandler:^(NSError *error) {
             if (error != nil) {
                 NSLog(@"登录失败%@", [error localizedDescription]);
                 dispatch_async(dispatch_get_main_queue(), ^{
                     hud.labelText = [error localizedDescription];
                     [hud hideAfterDelay:0.5];
                 });
             } else {
                 hud.labelText = NSLocalizedString(@"Login success", nil);
                 [hud hideAfterDelay:0.5];
                 
                 [[BDAccountManagerModel shareInstance] setLogin:YES];
                 
                 dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
                 dispatch_after(time, dispatch_get_main_queue(), ^{
                     if (_isJavascript) {
                         NSDictionary *dic = @{@"authorization":[BDAccountManagerModel shareInstance].authorization
                                               ,@"userId":[BDAccountManagerModel shareInstance].userId};
                         NSString *json = [NSString DataTOjsonString:dic];
                         self.block(json);
                     }
                     [self dismissViewControllerAnimated:YES completion:^{
                         if (_showShopcart) {
                             _tabBarController.selectedIndex = 3;
                         }
                     }];
                 });
             }
         }];
    }
}

- (IBAction)registerButtonPressed:(UIButton *)sender {
    
}

- (IBAction)findPwdButtonPressed:(UIButton *)sender {
    
}

- (IBAction)emailButtonPressed:(UIButton *)sender {
    
}


- (IBAction)closeButtonPressed:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
